package com.iraeta.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iraeta.common.AuthAccess;
import com.iraeta.entity.main.Srmmessage;
import com.iraeta.entity.main.type.SrmMessageType;
import com.iraeta.service.basic.SrmmessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController(value = "SrmMsgRecvController")
public class SrmMsgRecvController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(SrmMsgRecvController.class);
    @Autowired
    SrmmessageService srmmessageService;

    @PostMapping("srmmsgrecv")
    @AuthAccess
    public String srmMsgRecv(HttpServletRequest request){
        String message = request.getParameter("message");
        logger.info("srmMsgRecv___" + message);

        JSONObject msgJSONObject = JSON.parseObject(message);
        JSONObject dataJSONObject = msgJSONObject.getJSONObject("data");
        int orderId = 0;
        String action = "";
        String typeName = msgJSONObject.getString("type");
        int type = SrmMessageType.getSrmMessageTypeInt(typeName);
        if(typeName.equals("CAIGOU_MSG_PROCUREMENT_ORDER_CREATED")){
            orderId = dataJSONObject.getIntValue("procurementOrderId");
            action = dataJSONObject.getString("opMsgType");
        } else if(typeName.equals("CAIGOU_MSG_PROCUREMENT_SEND_GOODS_ACTION")){
            orderId = dataJSONObject.getIntValue("id");
            action = dataJSONObject.getString("action");
        } else if(typeName.equals("CAIGOU_MSG_PROCUREMENT_RECEIVEGOODS_ACTION")){
            orderId = dataJSONObject.getIntValue("id");
            action = dataJSONObject.getString("action");
        }
        if(action.equalsIgnoreCase("create")){
            Srmmessage srmmessage = new Srmmessage(type, typeName, orderId, message);
            srmmessageService.add(srmmessage);
        }
        return this.success();
    }
}
